package 二叉树;

import java.util.Stack;

/**
 * @author 会玩的洋洋
 * https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/
 */
public class _230_二叉搜索树中的第k小的元素 {
    /**
     * 中序遍历
     * @param root 根节点
     * @param k 第 k 小
     * @return int
     */
    public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            --k;
            if (k == 0) {
                break;
            }
            root = root.right;
        }
        return root != null ? root.val : 0;
    }
}
